// orders.js
const app = getApp()
const { API } = require('../../utils/api.js')
const { ensureLoggedIn } = require('../../utils/auth.js')

Page({
  data: {
    currentTab: 'all',
    orders: [],
    filteredOrders: [],
    userInfo: null
  },

  onLoad() {
    if (ensureLoggedIn()) {
      this.loadOrders()
      this.setPageTitle()
    }
  },

  setPageTitle() {
    const userInfo = app.globalData.userInfo
    if (userInfo && userInfo.role === 'admin') {
      wx.setNavigationBarTitle({
        title: '订单管理'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '我的订单'
      })
    }
  },

  onShow() {
    if (ensureLoggedIn()) {
      this.loadOrders()
    }
  },

  async loadOrders() {
    const userInfo = app.globalData.userInfo
    if (!userInfo || !userInfo.token) {
      console.log('未登录或token无效，跳转到登录页')
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    try {
      wx.showLoading({
        title: '加载订单...'
      })

      // 从后端获取订单列表
      const response = await API.getOrderList({
        status: this.data.currentTab === 'all' ? '' : this.data.currentTab,
        page: 1,
        size: 50
      })

      wx.hideLoading()

      if (response && response.list) {
        this.setData({
          orders: response.list,
          userInfo: userInfo
        })
        this.filterOrders()
      }
    } catch (error) {
      wx.hideLoading()
      console.error('获取订单列表失败:', error)
      
      // 如果API调用失败，尝试从本地缓存获取
      const allOrders = wx.getStorageSync('fuelOrders') || []
      let userOrders
      
      if (userInfo.role === 'admin') {
        userOrders = allOrders
      } else {
        userOrders = allOrders.filter(order => order.userId === userInfo.id)
      }
      
      userOrders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
      
      this.setData({
        orders: userOrders,
        userInfo: userInfo
      })
      this.filterOrders()
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab
    })
    this.filterOrders()
  },

  filterOrders() {
    const { orders, currentTab } = this.data
    
    let filtered
    if (currentTab === 'all') {
      filtered = orders
    } else {
      filtered = orders.filter(order => order.status === currentTab)
    }

    this.setData({
      filteredOrders: filtered
    })
  },



  getDifference(order) {
    if (order.status !== 'completed' || !order.actualAmount) {
      return 0
    }
    return parseFloat(order.actualAmount) - parseFloat(order.prepaidAmount)
  },

  goToFuel() {
    wx.switchTab({
      url: '/pages/fuel/fuel'
    })
  },

  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.logout()
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
          // 退出后跳转到登录页面
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    })
  }
})